package com.rexense.beacon.service;

import com.rexense.beacon.entity.Beacon;
import org.redisson.api.RBucket;
import org.redisson.api.RBuckets;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class BaseDataService {

    @Autowired
    private RedissonClient redisson;

    private final static String BEACON_PREFIX = "BEACON:";


    public Beacon getBeaconById(String id) {

        RBucket<Beacon> bucket = redisson.getBucket(BEACON_PREFIX + id);
        return bucket.get();
    }

    public void setBeacons(List<Beacon> beaconList) {
        beaconList.forEach(beacon -> {
            RBucket<Beacon> bucket = redisson.getBucket(BEACON_PREFIX + beacon.getBeaconId());
            bucket.set(beacon, 5, TimeUnit.HOURS);
        });
    }

    public List<Beacon> listBeacons(List<String> ids) {
        List<String> keys = ids.stream().distinct()
                .map(s -> BEACON_PREFIX + s)
                .collect(Collectors.toList());
        RBuckets buckets = redisson.getBuckets();
        Map<String, Beacon> stringObjectMap = buckets.get(keys.toArray(new String[]{}));
        return new ArrayList<>(stringObjectMap.values());
    }
}
